﻿using System;
using System.Collections.Generic;
using System.Text;

namespace LeafHttp
{
    /// <summary>
    /// Curl 解析器
    /// </summary>
    public class CurlParser
    {
        // 截取字符串，通过开始结束符
        private string SubString(string s, string a, string b)
        {
            var p = s.IndexOf(a) >= 0 ? (s.IndexOf(a) + a.Length) : 0;
            var l = s.IndexOf(b, p) >= 0 ? (s.IndexOf(b, p) - p) : (s.Length - p);
            return s.Substring(p, l);
        }

        // 解析请求头
        private Dictionary<string, string> ParseHeaders(string script)
        {
            var lines = script.Split('\n');
            var headers = new Dictionary<string, string>();
            for (var i = 0; i < lines.Length; ++i)
            {
                var line = lines[i].Trim();
                var is_header = line.Contains("-H");
                var is_cookie = line.Contains("Cookie:");
                if (is_header && !is_cookie)
                {
                    var clean_line = line.Replace("-H '", "").Replace("'", "");
                    var vals = clean_line.Split(':');
                    var key = vals[0].Trim();
                    var value = clean_line.Replace(key, "").Trim();
                    value = value.Replace(": ", "");
                    headers.Add(key, value);
                }
            }
            return headers;
        }

        // 解析Cookie
        private List<HttpCookie> ParseCookies(string script)
        {
            var lines = script.Split('\n');
            var cookies = new List<HttpCookie>();
            for (var i = 0; i < lines.Length; ++i)
            {
                var line = lines[i].Trim();
                var is_header = line.Contains("-H");
                var is_cookie = line.Contains("Cookie:") || line.Contains("cookie:");
                if (is_header && is_cookie)
                {
                    var clean_line = line.Replace("-H 'Cookie: ", "").Replace("-H 'cookie: ", "").Replace("'", "");
                    var items = clean_line.Split(';');
                    foreach (var item in items)
                    {
                        var vals = item.Split('=');
                        if (vals.Length == 2)
                        {
                            var key = vals[0].Trim();
                            var value = vals[1].Trim();
                            var cookie = new HttpCookie(key, value);
                            cookies.Add(cookie);
                        }
                    }
                }
            }
            return cookies;
        }

        /// <summary>
        /// 将Curl脚本转换为Http请求参数
        /// </summary>
        /// <param name="script">Curl脚本</param>
        /// <returns></returns>
        public RequestConfig CurlToRequestConfig(string script)
        {
            script = script.Replace("\\", "");
            var method = script.Contains("--data-raw") ? "POST" : "GET";
            var data = "";
            if (method == "POST")
            {
                data = SubString(script, "--data-raw '", "'");
            }

            var url = SubString(script, "curl '", "'");
            var headers = ParseHeaders(script);
            var cookies = ParseCookies(script);
            var requestConfig = new RequestConfig()
            {
                Url = url,
                Method = method,
                Headers = headers,
                Cookies = cookies,
                Data = data
            };
            return requestConfig;
        }
    }
}
